#encoding=utf-8

import datetime
import time
import urllib
import ujson

from django.contrib import admin
from django.db.models import Count, Max, F, Sum
from django.db.models.query import QuerySet
from django.utils.safestring import mark_safe
from django.utils.html import format_html
from django.contrib.auth.views import login
from django.contrib.auth.models import User,Group
from andy_manager import settings
import webconfig,fun

from websys.models import (
    UserProfile, HXHUserInfo, HXHPayInfo,PlatformInfo,HXHUserLogin,HXHConsumerInfo,
AgentInfo,UserInfo,GameInfo,RoomInfo,BannerInfo,TableInfo,UserRecharge,AgentRecharge,
AgentBank,WithdrawRecord,Feedback,ServerInfo,UserConsumeRecord,NewsInfo,SystemConfig,
)

import xadmin
from xadmin.views.list import ResultRow, ResultItem
from websys.admin.AdminLoginForm import AdminAuthenticationForm
from xadmin.views import website
from django.http import HttpResponseRedirect

website.LoginView.login_form = AdminAuthenticationForm
# Register your models here.


import xadmin
from models import (
LotteryInfo,IncrInfo,UserGamelog,TableInfo,RoomInfo,PayInfo,Detaile_Profit,Oper_Record,Pay_Image
)
#开奖数据页面
class LotteryInfoAdmin(object):
    list_display=('issue', 'result', 'extra','open_time',)#显示的数据
    search_fields=('issue',)#搜索的列名
    list_filter = ('extra','open_time')#过滤的列
    list_exclude=('id')#不可见的列
    fields=('open_time',)#只显示可编辑的列
    readonly_fields = ('issue', 'result', 'extra','open_time')#只可供读的字段数据

    #只读不能编辑修改
    def get_readonly_fields(self, obj=None):
        return self.readonly_fields
    #不能新建保存
    def save_models(self):
        return


# #用户列表
# class UserInfoAdmin(object):
#     list_display=('account','head','gold','register_time')#显示的字段数据
#     search_fields =('account',)#可供搜索的字段数据
#     list_filter = ('register_time',)  # 过滤的列
#     list_exclude = ('id','password') #不可见的列
#     fields =('head','register_time') #可编辑页显示的字段数据
#     readonly_fields = ('head','register_time','account','gold') #只可供读的字段数据
#
#     def get_readonly_fields(self,obj=None):
#         return self.readonly_fields
#
#     def save_models(self):
#         return

#游戏中玩家金币记录表
class IncrInfoAdmin(object):
    list_display=('user','issue','amount','changed_gold','remark','game_type')
    search_fields =['user__account','issue','game_type']
    list_filter = ('game_type',)  # 过滤的列
    list_exclude = ('id',)
    fields =('issue',)
    readonly_fields = ('issue','amount','changed_gold','remark')


    def get_readonly_fields(self):
        return self.readonly_fields

    def save_models(self):
        return


#玩家游戏数据日志表
class UserGamelogAdmin(object):
    list_display = ('user','issue','is_master','gain_goldpoint','bet_places','table_id','create_time')
    search_fields =('user__account','issue','table_id','is_master',)
    list_filter =('create_time','is_master')
    list_exclude =('id',)
    fields =('issue',)
    readonly_fields=('issue','is_master','gain_goldpoint','bet_places')

    def get_readonly_fields(self):
        return self.readonly_fields

    def save_models(self):
        return


#桌面游戏数据日志表
class TableInfoAdmin(object):
    list_display = ('issue','master_fee','table_fee','profit_fee','table_id','create_time')
    search_fields = ('issue','table_id')
    list_filter = ('create_time',)
    list_exclude = ('id',)
    fields = ('issue',)
    readonly_fields =('issue','master_fee','table_fee','profit_fee','create_time')

    def get_readonly_fields(self):
        return self.readonly_fields

    def save_models(self):
        return


#房间列表
class RoomInfoAdmin(object):
    list_display = ('room_type','name','min_join_gold','min_master_gold','grab_master_bets',
                    'player_bets','master_percent','table_fee','normal_profit_percent','sweep_profit_percent',
                    'table_max_player','grab_master_time','master_choose_seat_time',
                    'player_bet_time','player_max_bet_times','tables','create_time')
    search_fields = ('room_type','name','is_active')
    list_filter = ('create_time','is_active','room_type')
    list_exclude= ('id',)
    fields =('room_type','name','min_join_gold','min_master_gold','grab_master_bets',
                    'player_bets','master_percent','table_fee','normal_profit_percent','sweep_profit_percent',
                    'table_max_player','grab_master_time','master_choose_seat_time',
                    'player_bet_time','player_max_bet_times','tables',)

    #readonly_fields = ('room_type','name','min_join_gold','min_master_gold','grab_master_bets',
                    # 'player_bets','master_percent','table_fee','normal_profit_percent','sweep_profit_percent',
                    # 'table_max_player','grab_master_time','master_choose_seat_time',
                    # 'player_bet_time','player_max_bet_times','tables','create_time')

    #def get_readonly_fields(self):
        #return self.readonly_fields

    # def save_models(self):
    #     return
#订单充值数据表
class PayInfoAdmin(object):
    list_display = ('user','order_id','goldpoint','pay_time')
    search_fields = ('user__account','order_id')
    list_filter = ('pay_time',)
    list_exclude = ('id',)
    fields = ('order_id','goldpoint','pay_time')
    readonly_fields =('order_id','goldpoint','pay_time')

    def get_readonly_fields(self):
        return self.readonly_fields

    def save_models(self):
        return


class Detaile_ProfitAdmin(object):
    list_display=('nickname', 'account', 'agent_account', "agent_profit", "issue", "create_time")
    search_fields=('nickname', "account", "agent_account")
    list_filter = ('create_time',)
    list_exclude = ('id',)



class UserProfileAdmin(object):
    list_display=('user', 'nickname', 'sex', "telephone", "qq", "create_date")
    search_fields=('nickname', "telephone", "qq")
    list_filter = ('user',)

    def queryset(self):
        user = self.user
        queryset_all = super(UserProfileAdmin, self).queryset()
        if user.is_superuser:
            qs = queryset_all
        else:
            qs = queryset_all.filter(user=user)
        return qs


class HXHUserInfoAdmin(object):
    list_display=('uid','account','username', 'pf', 'pf1', "create_date","game_time")
    search_fields=('uid','account',)
    list_filter = ('uid', 'pf',)


class HXHPayInfoAdmin(object):
    list_display=('order_id', 'uid', 'money', "create_date")
    search_fields=('uid', 'order_id')
    list_filter = ('uid',)

class HXHConsumerInfoAdmin(object):
    list_display=( 'uid', 'amt','unit', "create_date")
    search_fields=('uid',)
    list_filter = ('uid',)

#登陆日志
class HXHUserLoginAdmin(object):
    list_display=('uid', 'pf', 'ip', "login_time")
    search_fields=('uid', 'pf')
    list_filter = ('uid', 'pf')
    #list_export = ('xls', 'xml', 'json')#导出类型
    # 这会显示一个下拉列表, 用户可以选择3秒或5秒刷新一次页面.
    #refresh_times = (3, 5)


#平台管理
class PlatformInfoAdmin(object):
    list_display=('pf_id', 'name', 'games', 'gameurl', "create_date")
    search_fields=('pf_id', 'name')
    list_filter = ('pf_id', 'name')

#游戏页面
class GameInfoAdmin(object):
    list_display=('id','gameid', 'gamename','feetype','roundkey','isfree','explain')
    search_fields=('gameid', 'gamename' )
    list_filter = ('gameid', 'gamename')
    def get_media(self):
        #<div id="type-dialogBox"></div>
        media = super(GameInfoAdmin, self).get_media()
        media.add_js((self.static('ButtonControl.js'),))
        return media
# #房间时长页面
# class RoomInfoAdmin(object):
#     list_display=('roomid', 'parid', 'roomname','consumerpoint')
#     search_fields=('roomid', 'parid__gameid','roomname')
#     list_filter = ('roomid', 'parid')
#banner页面
class BannerInfoAdmin(object):

    def image_tag(self, obj):
        return format_html('<img src="{}" style="width:180px;height:100px;" />'.format(obj.img.url))
    image_tag.short_description = '图片'

    list_display=('name','image_tag','app','url')
    #search_fields=('name')
    #list_filter = ('name')
# #开桌页面
# class TableInfoAdmin(object):
#     #pass
#     list_display=('gameid','uid','roomid','time','point','game_time')
#     search_fields=('roomid','uid__nickname')
#     list_filter = ('gameid','uid','game_time')
#     list_exclude=('id','isbanker','game_status','round','recordid','server','playnum','openparam')
#     def queryset(self):
#         queryset_all = super(TableInfoAdmin, self).queryset()
#         qs = queryset_all.filter(game_time__isnull=False)
#         return qs
#     #添加资源
#     def get_media(self):
#         #<div id="type-dialogBox"></div>
#         media = super(TableInfoAdmin, self).get_media()
#         #media.add_js((self.static('ButtonControl.js'),))
#         return media
#     def save_models(self):#重写保存操作
#         return

#服务器页面
class ServerInfoAdmin(object):
    list_display=('game', 'ip', 'port','create_time')
    search_fields=( 'ip','port')
    list_filter = ('game',  'ip','port')
    list_exclude=('id','create_time',)


#反馈页面
class FeedbackAdmin(object):
    list_display=('typeid', 'gameid', 'problem', 'username','phone','create_time','status')
    search_fields=('username', 'problem')
    list_filter = ('uid','typeid', 'gameid','status')
    list_exclude=('id','create_time','status')
    fields=('typeid', 'problem','replay','status')#只显示可编辑的列

    def status_state(self, obj):#自定义列
        if obj.status == 0:
            return u'<span style="color:red;font-weight:bold">{0}</span>'.format(u"未回复")
        elif obj.status == 1:
            return u'<span style="color:green;font-weight:bold">{0}</span>'.format(u"已回复")
        else:
            return u'<span style="color:orange;font-weight:bold">%s</span>' % (u"其它",)
    status_state.short_description = u'状态'
    status_state.allow_tags = True

    def save_models(self):#重写保存操作
        obj = self.new_obj
        #是修改要记录操作者的uid
        if (self.org_obj is not None):
            obj.operid=self.user
        obj.save()

        #添加资源
    def get_media(self):
        #<div id="type-dialogBox"></div>
        media = super(FeedbackAdmin, self).get_media()
        media.add_js((self.static('ButtonControl.js'),))
        return media

#获取是否代理或管理员
def CheckIsAgent(_uobj):
    login_uid = _uobj.username
    if (AgentInfo.objects.filter(account=login_uid).exists()):
        return AgentInfo.objects.get(account=login_uid)
    else:
        return None

#代理充值页面
class AgentRechargeAdmin(object):
    #pass
    list_display=('operid','agentid','username','money','amount','create_time')
    search_fields=('operid','agentid')
    list_filter = ('operid','agentid')
    #添加资源
    def get_media(self):
        #<div id="type-dialogBox"></div>
        media = super(AgentRechargeAdmin, self).get_media()
        media.add_js((self.static('ButtonControl.js'),))
        return media

        #玩家房卡页面
class UserRechargeAdmin(object):
    from admin.myfilter import UserFilter
    list_display=('nickname','amount','money','appid','create_time')
    search_fields=('nickname','uid')
    list_filter = ('appid','nickname',UserFilter)
    list_exclude = ("id","operid","gamedata","classid","is_sync")
    #添加资源
    def get_media(self):
        #<div id="type-dialogBox"></div>
        media = super(UserRechargeAdmin, self).get_media()
        media.add_js((self.static('ButtonControl.js'),))
        return media

    def queryset(self):
        queryset_all = super(UserRechargeAdmin, self).queryset()
        if not self.user.is_superuser:

            a_info=CheckIsAgent(self.user)
            if a_info:
                qs = queryset_all.filter(classid__startswith=a_info.classid)

                return qs

        return queryset_all

    #配置页面
class UserConsumeRecordAdmin(object):
    list_display=('uid','typeid','consumepoint','lastpoint','create_time','remark',)
    search_fields=('uid__nickname',)
    list_filter=('uid','typeid',)
    list_exclude=('id','gameid','requestkey','isread',)
    def save_models(self):
        return

#代理银行页面
class AgentBankAdmin(object):
    #pass
    list_display=('bankcard','banktype','truename','phone','branch')
    search_fields=('truename','bankcard','branch')
    list_filter = ('truename','banktype')
    fields=('truename','phone','bankcard','banktype','branch')
    list_exclude = ("id","agentid")
    user_type=0

    def get_model_form(self, **kwargs):
        if self.user.is_superuser:
            self.user_type=1
            fields=('truename','phone','bankcard','banktype','branch','agentid')
        return super(AgentBankAdmin, self).get_model_form(**kwargs)

    def queryset(self):
        queryset_all = super(AgentBankAdmin, self).queryset()
        if not self.user.is_superuser:
            a_info=CheckIsAgent(self.user)
            if a_info:
                qs = queryset_all.filter(agentid_id=a_info.id)

                return qs

        return queryset_all

    def save_models(self):#重写保存操作
        obj = self.new_obj
        #是新增获取当前登陆的代理信息
        if (self.org_obj is None):
            ag_info=CheckIsAgent(self.user)
            obj.agentid=ag_info
        obj.save()
    #添加资源
    def get_media(self):
        #<div id="type-dialogBox"></div>
        media = super(AgentBankAdmin, self).get_media()
        if self.user.is_superuser:#管理员不能添加，修改代理的银行
            media.add_js((self.static('ButtonControl.js'),))
        return media


#额度操作记录
class Oper_RecordAdmin(object):
    list_display = ('account', 'account_type', 'oper_type', 'number', 'opers', 'create_time',)
    search_fields = ('account',)
    list_filter = ('account_type', 'oper_type',)
    list_exclude = ('id',)


    def queryset(self):
        queryset_all = super(Oper_RecordAdmin, self).queryset()
        if not self.user.is_superuser:
            a_info = CheckIsAgent(self.user)
            if a_info:
                qs = queryset_all.filter(opers=a_info.account)

                return qs

        return queryset_all


#支付二维码管理
class Pay_ImageAdmin(object):
    list_display = ('pay_way', 'pay_image','create_time',)
    search_fields = ('pay_way',)
    #list_filter = ('', 'oper_type',)
    list_exclude = ('id','remark',)

    def save_models(self):#重写保存操作
        obj = self.new_obj
        import shutil,os

        obj.save()
        file_name=str(str(obj.pay_image).split('/')[2]).split('.')[0]
        if int(obj.pay_way) == 1:
            if os.path.exists('websys/static/%s.png'%file_name):
                if os.path.exists('websys/static/weichat.png'):
                    os.remove('websys/static/weichat.png')
                os.rename('websys/static/%s.png'%file_name,'websys/static/weichat.png')
                shutil.copy('websys/static/weichat.png','/usr/local/nginx/html/jdb_client/pay_img')
                #shutil.copy('websys/static/weichat.png', 'websys/view')
        elif int(obj.pay_way)==2:
            if os.path.exists('websys/static/%s.png'%file_name):
                if os.path.exists('websys/static/alipay.png'):
                    os.remove('websys/static/alipay.png')
                os.rename('websys/static/%s.png'%file_name,'websys/static/alipay.png')
                shutil.copy('websys/static/alipay.png', '/usr/local/nginx/html/jdb_client/pay_img')
                #shutil.copy('websys/static/alipay.png', 'websys/view')
        # #print '--------------------22222222222----------',str(obj.pay_image).split('/')[2]
        # if int(obj.pay_way) == 1:
        #     #shutil.copy('websys/static/weichat.png','/usr/local/nginx/html/jdb_client/pay_img')
        #     shutil.copy('websys/static/weichat.png', 'websys/view')
        # elif int(obj.pay_way) == 2:
        #     #shutil.copy('websys/static/alipay.png', '/usr/local/nginx/html/jdb_client/pay_img')
        #     shutil.copy('websys/static/alipay.png', 'websys/view')
        #     print '---------------8888888888---'




#xadmin.site.register(AgentInfo, TwitterUserAdmin)

# code = self.cleaned_data.get('password')
#         return forms.ValidationError(self.error_messages['codeerror'])
from xadmin.forms import AdminAuthenticationForm
def insert_into_record(obj, request):
    is_create = not bool(obj.id)
    operation_type = OperationRecordInfo.CONST_ADD if is_create else OperationRecordInfo.CONST_ALTER
    log = ["{}:{}".format(field.verbose_name, obj._get_FIELD_display(field)) for field in obj._meta.fields]
    #for m2m in obj._meta.many_to_many:
    #    log.append("{}:({})".format(m2m.verbose_name, ",".join([unicode(sld) for sld in getattr(obj, m2m.get_attname()).all()])))
    log = ",".join(log)
    table_name = obj._meta.verbose_name_plural
    user = request.user
    OperationRecordInfo.objects.create(user=user, table_name=table_name, operation_type=operation_type, result=log, create_date=datetime.datetime.now())

#全局配置
from xadmin import views
class BaseSetting(object):
    enable_themes = True
    use_bootswatch = True

class AdminSettings(object):
    # 设置base_site.html的Title
    site_title = '游戏管理系统'
    # 设置base_site.html的Footer
    site_footer = 'Winhong Inc.'
    menu_style = 'default'
    #xadmin.site.

    # 菜单设置
    def get_site_menu(self):
        #print(self.user,'_------***********')
        """``FAQ:如何定制系统菜单``\n
        用于给子类复写的方法，开发者可以在子类或 OptionClass 中复写该方法，返回自己定义的网站菜单。菜单的格式为::

            ({
                "title": "菜单标题", "perm": "权限标示",
                "icon": "图标的 css class", "url": "菜单url",
                "menus": [...]    # 子菜单项
            })

        菜单项的 ``perm`` 和 ``url`` 如果是基于 Model 的，可以使用 xadmin 提供的便利方法
        :meth:`BaseAdminObject.get_model_perm` 和 :meth:`BaseAdminObject.get_model_url`。举例说明创建菜单::

            class AdminSettings(object):

                def get_site_menu(self):
                    return (
                        {'title': '内容管理', 'perm': self.get_model_perm(Article, 'change'), 'menus':(
                            {'title': '游戏资料', 'icon': 'info-sign', 'url': self.get_model_url(Article, 'changelist') + '?_rel_categories__id__exact=2'},
                            {'title': '网站文章', 'icon': 'file', 'url': self.get_model_url(Article, 'changelist') + '?_rel_categories__id__exact=1'},
                        )},
                        {'title': '分类管理', 'perm': self.get_model_perm(Category, 'change'), 'menus':(
                            {'title': '主要分类', 'url': self.get_model_url(Category, 'changelist') + '?_p_parent__isnull=True'},
                            {'title': '游戏资料', 'url': self.get_model_url(Category, 'changelist') + '?_rel_parent__id__exact=2'},
                        )},
                    )

            site.register(CommAdminView, AdminSettings)

        """
        if self.user.is_superuser:
            SITE_CONFIG_MENU= (
                        {'title': '数据报表', 'perm': self.get_model_perm(AgentInfo, 'change'), 'menus':(
                            {'title': '代理列表', 'url': self.get_model_url(AgentInfo, 'changelist')},
                            {'title': '玩家管理', 'url': self.get_model_url(UserInfo, 'changelist') },
                            {'title': '提成统计', 'url': '/xadmin/agent_profit/profit'},
                            {'title': '提成明细', 'url': '/xadmin/gamereport/detaile_profit'},
                            {'title': '游戏数据统计', 'url': '/xadmin/gamereport/sytem_data'},
                            {'title': '额度操作记录', 'url': self.get_model_url(Oper_Record, 'changelist')},
                            #{'title': '提现记录', 'url': self.get_model_url(WithdrawRecord, 'changelist') },
                            {'title': '快8开奖日志', 'url': self.get_model_url(LotteryInfo, 'changelist')},
                            {'title': '玩家金币日志', 'url': self.get_model_url(IncrInfo, 'changelist')},
                            {'title': '游戏数据日志', 'url': self.get_model_url(UserGamelog, 'changelist')},
                            {'title': '充值订单日志', 'url': self.get_model_url(PayInfo, 'changelist') },
                            # {'title': '充值报表', 'url': '/xadmin/agent/report'},
                            # {'title': '钻石消耗统计', 'url': '/xadmin/gamereport/diamond'},
                            # #{'title': '代理局数统计', 'url': '/xadmin/agent_gather/gather'},
                            # {'title': '代理银行', 'url': self.get_model_url(AgentBank, 'changelist')},
                            # {'title': '钻石明细', 'url': self.get_model_url(UserConsumeRecord, 'changelist')},
                            #{'title': '分享统计', 'url': '/xadmin/gamereport/share'},
                        )},

                        {'title': '游戏管理', 'perm': self.get_model_perm(GameInfo, 'change'), 'menus':(
                            # {'title': '在线统计', 'url': '/xadmin/gamereport/online'},
                            # {'title': '平台列表', 'url': self.get_model_url(PlatformInfo, 'changelist')},
                            # {'title': '游戏列表', 'url': self.get_model_url(GameInfo, 'changelist')},
                            {'title': '房间管理', 'url': self.get_model_url(RoomInfo, 'changelist') },
                            {'title': '桌面游戏数据日志表', 'url': self.get_model_url(TableInfo, 'changelist')},
                            {'title': '支付二维码管理', 'url': self.get_model_url(Pay_Image, 'changelist')},
                            # {'title': '游戏服务器', 'url': self.get_model_url(ServerInfo, 'changelist') },
                            # {'title': '开桌日志', 'url': self.get_model_url(TableInfo, 'changelist') },
                            # {'title': '开桌统计', 'url': '/xadmin/gamereport/table' },
                            # {'title': 'Banner管理', 'url': self.get_model_url(BannerInfo, 'changelist') },
                            # {'title': '玩家反馈', 'url': self.get_model_url(Feedback, 'changelist') },
                            # {'title': '消息中心', 'url': self.get_model_url(NewsInfo, 'changelist') },
                            # {'title': '系统配置', 'url': self.get_model_url(SystemConfig, 'changelist') },
                        )},
                    )
            #添加代理组1
            if Group.objects.filter(pk=1).count()==0:
                Group.objects.create(name='agent_group')
            # try:
            #     if(xadmin.site._registry.has_key(AgentInfo)):
            #         xadmin.site.unregister(AgentInfo)
            #     if(xadmin.site._registry.has_key(UserInfo)):
            #         xadmin.site.unregister(UserInfo)
            #     if(xadmin.site._registry.has_key(AgentBank)):
            #         xadmin.site.unregister(AgentBank)
            # except:
            #     pass
        else:

            #最后一级没有代理列表管理
            #print(dir(self))
            from django.contrib.sessions.models import Session
            session_key=None
            if('_auth_user_id' in self.request.session):
                session_key=self.request.session[ '_auth_user_id']
            # print(self.request.session.keys(),'---session_key---',session_key)
            # session = Session.objects.get(pk=session_key)
            # print(session.session_data);                 # 返回session的存储（加密过）
            # print(session.get_decoded());                # 返回session的数据结构（加过解码）
            # print(session.expire_date);

            ag_arr=AgentInfo.objects.filter(account=self.user.username)
            if len(ag_arr)==0:#删除了，清了用户,跳转
                #self.request.session.clear()
                #self.request.session.set_expiry()
                # self.user.delete()
                # if('_auth_user_id' in self.request.session):
                #     del self.request.session[ '_auth_user_id']
                # return
                SITE_CONFIG_MENU= (
                    {'title': '代理端管理', 'perm': self.get_model_perm(AgentInfo, 'change'), 'menus':(
                                {'title': '我的代理', 'url': self.get_model_url(AgentInfo, 'changelist')},
                                {'title': '我的信息', 'url': '/xadmin/agent/info'},
                                {'title': '我的银行', 'url': self.get_model_url(AgentBank, 'changelist')},
                                {'title': '提现记录', 'url': self.get_model_url(WithdrawRecord, 'changelist') },
                                {'title': '玩家列表', 'url': self.get_model_url(UserInfo, 'changelist') },
                                {'title': '玩家充币记录', 'url': self.get_model_url(UserRecharge, 'changelist') },
                            )},
                )
                SITE_CONFIG_MENU= (
                        {'title': '游戏管理', 'perm': self.get_model_perm(GameInfo, 'changelist'), 'menus':(
                            #{'title': '提现记录', 'url': self.get_model_url(WithdrawRecord, 'changelist') },
                            # {'title': '充值记录', 'url': self.get_model_url(UserRecharge, 'changelist') },
                            {'title': '充值报表', 'url': '/xadmin/agent/report'},
                            {'title': '金钻消耗统计', 'url': '/xadmin/gamereport/diamond'},
                            {'title': '在线统计', 'url': '/xadmin/gamereport/online'},
                            # {'title': '游戏列表', 'url': self.get_model_url(GameInfo, 'changelist')},
                            # # {'title': '房间管理', 'url': self.get_model_url(RoomInfo, 'changelist') },
                            # # {'title': '游戏服务器', 'url': self.get_model_url(ServerInfo, 'changelist') },
                            #
                            # {'title': '开桌日志', 'url': self.get_model_url(TableInfo, 'changelist') },
                            # {'title': 'Banner管理', 'url': self.get_model_url(BannerInfo, 'changelist') },
                            # {'title': '玩家反馈', 'url': self.get_model_url(Feedback, 'changelist') },
                        )},
                    )
                #SITE_CONFIG_MENU= ()
            else:
                SITE_CONFIG_MENU= (
                    {'title': '代理端管理', 'perm': self.get_model_perm(AgentInfo, 'change'), 'menus':(
                        #{'title': '代理列表', 'url': self.get_model_url(AgentInfo, 'changelist')},
                        {'title': '我的信息', 'url': '/xadmin/agent/info'},
                        {'title': '玩家管理', 'url': self.get_model_url(UserInfo, 'changelist')},
                        {'title': '提成统计', 'url': '/xadmin/agent_profit/profit'},
                        {'title': '提成明细', 'url': '/xadmin/gamereport/my_detaile_profit'},
                        {'title': '额度操作记录', 'url': self.get_model_url(Oper_Record, 'changelist')},
                        # {'title': '提成明细', 'url': self.get_model_url(Detaile_Profit, 'changelist')},
                        # {'title': '提现记录', 'url': self.get_model_url(WithdrawRecord, 'changelist') },
                        {'title': '快8开奖日志', 'url': self.get_model_url(LotteryInfo, 'changelist'),'perm': self.get_model_perm(LotteryInfo, 'view')},
                            )},
                )
                #return HttpResponseRedirect('/xadmin/logout/')  #跳转到index界面
                ag_info=AgentInfo.objects.get(account=self.user.username)
                if len(ag_info.classid)/3>=webconfig.AGENT_LEVEL:
                    tmp_menu=list(SITE_CONFIG_MENU[0]['menus'])
                    # del tmp_menu[0]
                    # SITE_CONFIG_MENU[0]['menus']=tuple(tmp_menu)
                    # try:
                    #     if(xadmin.site._registry.has_key(AgentInfo)):
                    #         xadmin.site.unregister(AgentInfo)
                    # except:
                    #     pass
                #xadmin.site.register(AgentBank,AgentBankAdmin)
                #更新登陆时间，ip
                ag_info.login_time=datetime.datetime.now()
                ag_info.login_ip=fun.GetIP(self.request)
                ag_info.save()

        return  SITE_CONFIG_MENU
        #return None

#xadmin.site.register(views.BaseAdminView,BaseSetting)


#注册model到页面
# xadmin.site.register(UserProfile, UserProfileAdmin)
# xadmin.site.register(HXHUserInfo, HXHUserInfoAdmin)
# xadmin.site.register(HXHPayInfo, HXHPayInfoAdmin)
# xadmin.site.register(HXHConsumerInfo, HXHConsumerInfoAdmin)
# xadmin.site.register(HXHUserLogin, HXHUserLoginAdmin)

#麻将的#xadmin.site.register(AgentInfo, AgentInfoAdmin)
#xadmin.site.register(UserInfo, UserInfoAdmin)
from websys.admin import (
    agent,userinfo
)

# xadmin.site.register(Feedback, FeedbackAdmin)
# xadmin.site.register(PlatformInfo, PlatformInfoAdmin)
# xadmin.site.register(GameInfo, GameInfoAdmin)
# xadmin.site.register(RoomInfo, RoomInfoAdmin)
# xadmin.site.register(BannerInfo, BannerInfoAdmin)
# xadmin.site.register(TableInfo, TableInfoAdmin)
# xadmin.site.register(ServerInfo, ServerInfoAdmin)
# xadmin.site.register(UserConsumeRecord, UserConsumeRecordAdmin)
# xadmin.site.register(UserRecharge, UserRechargeAdmin)
# xadmin.site.register(AgentBank,AgentBankAdmin)
#其它
#消息页面
class NewsInfoAdmin(object):
    list_display=('title','content','create_time')
    search_fields=('title',)
    #list_filter=('title','typeid',)
#xadmin.site.register(NewsInfo,NewsInfoAdmin)
#配置页面
class SystemConfigAdmin(object):
    list_display=('typeid','content','remark','create_time')
    search_fields=('typeid',)
    #list_filter=('title','typeid',)
#xadmin.site.register( SystemConfig, SystemConfigAdmin)

xadmin.site.register(LotteryInfo, LotteryInfoAdmin)
xadmin.site.register(IncrInfo,IncrInfoAdmin)
xadmin.site.register(UserGamelog,UserGamelogAdmin)
xadmin.site.register(TableInfo,TableInfoAdmin)
xadmin.site.register(RoomInfo,RoomInfoAdmin)
xadmin.site.register(PayInfo,PayInfoAdmin)
xadmin.site.register(Oper_Record,Oper_RecordAdmin)
xadmin.site.register(views.CommAdminView,AdminSettings)
xadmin.site.register(Pay_Image,Pay_ImageAdmin)

#报表
from websys.view import (report)

#xadmin.site.register(views.CommAdminView,AdminSettings)
